package guida.ccf.gzuexaminesystem.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import guida.ccf.gzuexaminesystem.entity.StudentInfo;
import guida.ccf.gzuexaminesystem.service.StudentInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * 重构 Spring Security 的查询用户的方式
 */
@Slf4j
@Service
public class StudentInfoDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private StudentInfoService userService;

    @Override
    public UserDetails loadUserByUsername(String username) {

        try {
            log.info("学生登录判断方法执行...");

            // 查询用户信息
            LambdaQueryWrapper<StudentInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(StudentInfo::getStudentId, username);
            StudentInfo user = userService.getOne(lambdaQueryWrapper);

            // 查询权限信息
            String roleType = user.getRoleType();

            // 返回
            return new LoginStudentInfo(user, Collections.singletonList(roleType));
        } catch (Exception e) {
            throw new RuntimeException("用户名或密码错误!");

        }
    }
}
